layui.use(['table','element','upload'], function() {
var table = layui.table,
    $ = layui.jquery,
    layer = layui.layer,
    form = layui.form,
    laytpl = layui.laytpl,
    message = parent.message,
    upload = layui.upload;
	element = layui.element;
var tableIns = table.render({
    elem: '#demo',
    height: 'full-132', //容器高度
    url: '../app/version/list?_'+$.now(),
    where: {sidx: '', order: 'desc'},
    page: true,
    id: 'demo',
    limit: 20,
    cols: [
        [{
            checkbox: true,
            fixed: true
        }, {
            field: 'versionCode',
            title: '版本号',
            width: 100,
            sort: true
        },
        {
            field: 'type',
            title: '类型',
            width: 200,
            sort: true,
            templet: '#typetpl'
        }, {
            field: 'url',
            title: '下载链接',
            width: 150
        }, {
            field: 'createTime',
            title: '创建时间',
            width: 350
        },{
            fixed: 'right',
            title: '操作',
            width: 300,
            align: 'center',
            toolbar: '#barDemo'
        }]
    ],
    done: function(res, curr, count) {
    	
    },
    loading: true,
});
form.render(null, 'kit-search-form');
$('#kit-search-more').on('click', function() {
    $('.kit-search-mored').toggle();
});

var liCTextarea,tiaoJTextarea,caiLTextarea,locationTextarea;
//监听工具条
table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data; //获得当前行数据
    var layEvent = obj.event; //获得 lay-event 对应的值
    var tr = obj.tr; //获得当前行 tr 的DOM对象

    if (layEvent === 'del') { //删除
        layer.confirm('确定删除该数据', function(index) {
            layer.close(index);
            //向服务端发送删除指令
            var userIds = Array();
            userIds.push(data.userId);
            $.ajax({
        		type: "POST",
        	    url: "../app/verson/delete",
        	    data: JSON.stringify(userIds),
        	    dataType: 'JSON',
        	    contentType: 'application/json',
        	    success: function(res){
        	    	if (res.code==0) {
        	        	message.show({
        	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
        	                msg:'操作成功'//提示信息
        	            });
        	        	obj.del(); //删除对应行（tr）的DOM结构
        	        	//tableIns.reload({where: {sidx: '', order: 'desc'}});
        	        } else {
        	        	layer.msg(res.msg, {icon: 2});
        	        }
        		}
        	});
        });
    } else if (layEvent === 'edit') { //编辑
    	$.get("../app/version/info/"+data.id, function(res){
			if(res.code==0){
				$.get("../app/version/select", function(r){
					var d = {
						appversion:{
							id:data.id,
							versionCode: data.versionCode,
							type:data.type,
							url:data.url
						}
			        };
					var fileFlg = false;
			        laytpl($('#edit-tpl').html()).render(d, function(html) {
			        	var n = 0, timer;
			            layer.open({
			                type: 1,
			                title: '修改',
			                content: html,
			                maxmin: true,
			                skin: 'layui-layer-rim', //加上边框
			                area: '600px',
			                btn: ['提交', '取消'],
			                yes: function(index, layero) {
			                    editIndex = index;
			                    $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
			                    var _appurl = $("#appurl").attr("src");
			                  
			                    if(fileFlg){
			                    	//uploadInst.config.data={id:$("#id").val(),versionCode:$("#versionCode").val(),type:$("#type").val()};
			                    	$("#myprogress").show();
			                    	$('#formEdit').click();
			                    	 //模拟loading
                  	    	      timer = setInterval(function(){
                  	    	        n = n + Math.random()*10|0;  
                  	    	        if(n>80){
                  	    	          n = 80;
                  	    	          clearInterval(timer);
                  	    	         // othis.removeClass(DISABLED);
                  	    	        }
                  	    	        element.progress('demo', n+'%');
                  	    	      }, 300+Math.random()*1000);
                  	    	      
			                    }
			                    else{
			                    	var appversion = new Object(); 
			                    	appversion.versionCode=$("#versionCode").val();
			                    	appversion.type=$("#type").val();
			                    //	var json = JSON.stringify(appversion); 
    	                    		saveOrUpdate(appversion);
    	                    		editIndex && layer.close(editIndex);
			                    }
			                    
			                },
			                btn2: function(index, layero) {
			                	layer.close(index); //关闭弹出层
			                    $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
			                    return false;
			                },
			                success: function() {
			                    form.render(null, 'form-edit');
			                    
			                }
			            });
			            var uploadInst = upload.render({
	                        elem: '#menuLogoButton',
	                        url: '/comm-cg/app/version/update2',
	                        accept: 'file',
	                        auto: false, //选择文件后不自动上传
	                        bindAction: '#formEdit', //指向一个按钮触发上传
	                        choose: function(obj){
	                    	    //将每次选择的文件追加到文件队列
	                    	    var files = obj.pushFile();
	                    	    //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
	                    	    obj.preview(function(index, file, result){
	                    	      //这里还可以做一些 append 文件列表 DOM 的操作
	                    	    	console.log(file.name);
	                    	      $('#appurl').attr('value', "http://47.94.220.217/comm-cg/apkfile"+file.name); //图片链接（base64）
	                    	      
	                    	      fileFlg=true;
	                    	      //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
	                    	      //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
	                    	      
	                    	    });
	                    	  }
	                        ,done: function(res){
	                        	console.log(res);
	                          //如果上传失败
	                          if(res.code != 0){
	                        	  layer.msg(res.msg, {icon: 2});
	                          }else{
	                        	  
//	                        	  message.show({
//	              	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
//	              	                msg:'操作成功'//提示信息
//	              	              });
	                        	  //
	                        	element.progress('demo', '100%');
	                        	clearInterval(timer);
	              	        	tableIns.reload({where: {order: 'desc'}});
	              	        	//上传
	              	        	var appversion = new Object(); 
	              	        	appversion.id=$("#id").val();
		                    	appversion.versionCode=$("#versionCode").val();
		                    	appversion.type=$("#type").val();
		                    	appversion.url = res.msg;
		                    	//var json = JSON.stringify(appversion); 
	                    		saveOrUpdate(appversion);
	              	        	
	              	        	editIndex && layer.close(editIndex);
	                          }
	                          //上传成功
	                        }
	                        ,error: function(){
	                          
	                        }
	                      });
			        });
				});
			}else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		});
    }
});

var roleList;
$(function(){
	$.get("../app/role/select", function(r){
		roleList = r.list;
	});
});

$('.kit-search-btns').children('a').off('click').on('click', function() {
    var $that = $(this),
    action = $that.data('action');
    switch (action) {
        case 'add':
        	$.get("../app/version/select", function(r){
        		if(r.code==0){
        			var d = {
        					appversion:{
    							id:'',
    							url: '',
    							versionCode:'',
    							type:''
    						}
                    };
        			var fileFlg = false;
                    //渲染
                    laytpl($('#edit-tpl').html()).render(d,
                        function(html) {
                    	var n=0,timer;
                            layer.open({
                                type: 1,
                                title: '新增',
                                content: html,
                                skin: 'layui-layer-rim', //加上边框
                                area: '600px',
                                btn: ['提交','取消'],
                                yes: function(index, layero) {
                                    editIndex = index;
                                    $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
                                    var _appurl = $("#appurl").attr("src");
    			                    if(fileFlg){
    			                    	//uploadInst.config.data={versionCode:$("#versionCode").val(),type:$("#type").val()};
    			                    	$("#myprogress").show();
    			                    	$('#formEdit').click();
    			                    	 //
    	                  	    	      timer = setInterval(function(){
    	                  	    	        n = n + Math.random()*10|0;  
    	                  	    	        if(n>80){
    	                  	    	          n = 80;
    	                  	    	          clearInterval(timer);
    	                  	    	         // othis.removeClass(DISABLED);
    	                  	    	        }
    	                  	    	        element.progress('demo', n+'%');
    	                  	    	      }, 300+Math.random()*1000);
    			                    }
    			                    else{
    			                    	var appversion = new Object(); 
    			                    	appversion.versionCode=$("#versionCode").val();
    			                    	appversion.type=$("#type").val();
    			                    //	var json = JSON.stringify(appversion); 
        	                    		saveOrUpdate(appversion);
        	                    		editIndex && layer.close(editIndex);
    			                    }
                                },
                                btn2: function(index, layero) {
                                	editIndex=index;
				                	editIndex && layer.close(editIndex);
                                    $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
                                    return false;
                                },
                                success: function() {
                                    form.render(null, 'form-edit');
                                }
                            });
                            var uploadInst = upload.render({
    	                        elem: '#menuLogoButton',
    	                        url: '/comm-cg/app/version/update2',
    	                        accept: 'file',
    	                        auto: false, //选择文件后不自动上传
    	                        bindAction: '#formEdit', //指向一个按钮触发上传
    	                        choose: function(obj){
    	                    	    //将每次选择的文件追加到文件队列
    	                    	    var files = obj.pushFile();
    	                    	    //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
    	                    	    obj.preview(function(index, file, result){
    	                    	      //这里还可以做一些 append 文件列表 DOM 的操作
    	                    	      $('#appurl').attr('value', "http://47.94.220.217/comm-cg/apkfile/"+file.name); 
    	                    	      fileFlg=true;
    	                    	      //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
    	                    	      //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
    	                    	    });
    	                    	  }
    	                        ,done: function(res){
    	                        	console.log(res);
    	                          //如果上传失败
    	                          if(res.code != 0){
    	                        	  layer.msg(res.msg, {icon: 2});
    	                          }else{
//    	                        	  message.show({
//    	              	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
//    	              	                msg:'操作成功'//提示信息
//    	              	            });
    	                        	  element.progress('demo', '100%');
    		                        	clearInterval(timer);
    		              	        	tableIns.reload({where: {order: 'desc'}});
    		              	        	//上传
    		              	        	var appversion = new Object(); 
    		              	        	appversion.id=$("#id").val();
    			                    	appversion.versionCode=$("#versionCode").val();
    			                    	appversion.type=$("#type").val();
    			                    	appversion.url = res.msg;
    			                    	//var json = JSON.stringify(appversion); 
    		                    		saveOrUpdate(appversion);
    		              	        	
    		              	        	editIndex && layer.close(editIndex);
    	              	        	tableIns.reload({where: {order: 'desc'}});
    	                          }
    	                          //上传成功
    	                        }
    	                        ,error: function(){
    	                        	
    	                        }
    	                      });
                        });
        		}else {
    	        	layer.msg(r.msg, {icon: 2});
    	        }
        	});
            break;
        case 'del-bulk':
            var d = table.checkStatus('demo');
            if (d.data.length === 0) {
                layer.msg('请选择要删除的数据');
                return;
            }
            var data = d.data,
                ids = [];
            layui.each(data, function(index, item) {
                ids.push(item.id);
            });
            layer.confirm('确定删除选中的数据', function(index) {
            	layer.close(index);
                //向服务端发送删除指令
                $.ajax({
            		type: "POST",
            	    url: "../app/version/delete",
            	    data: JSON.stringify(ids),
            	    dataType: 'JSON',
            	    contentType: 'application/json',
            	    success: function(res){
            	    	if (res.code==0) {
            	        	message.show({
            	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
            	                msg:'操作成功'//提示信息
            	            });
            	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
            	        } else {
            	        	layer.msg(res.msg, {icon: 2});
            	        }
            		}
            	});
            });
            break;
        }
    });

var saveOrUpdate = function (datas) {
	var url = datas.id == null ? "../app/version/save" : "../app/version/update";
	$.ajax({
		type: "POST",
	    url: url,
	    data: JSON.stringify(datas),
	    dataType: 'JSON',
	    contentType: 'application/json',
	    success: function(res){
	    	if (res.code==0) {
	        	message.show({
	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
	                msg:'操作成功'//提示信息
	            });
	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
	        } else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		}
	});
}

//监听搜索表单提交
form.on('submit(search)', function(data) {
	if(data.field.mobile!=""||data.field.status!=""||data.field.email!=""){
		$('.kit-search-mored').toggle();
	}
    if(data.field.status==""){
    	//带条件查询
        tableIns.reload({
        	where: {
        		sidx: '', order: 'desc',
        		versionCode: data.field.versionCode
        	}
        });
    }else{
    	//带条件查询
        tableIns.reload({
        	where: {
        		sidx: '', order: 'desc',
        		versionCode: data.field.versionCode
        	}
        });
    }
    return false;
});
var editIndex;
//form.on('submit(formEdit)', function(data) {
//	saveOrUpdate(data.field);
//	editIndex && layer.close(editIndex); //关闭弹出层
//    return false;
//});

});
